import 'package:flutter/material.dart';
import 'package:flutter_structure/modules/grallery/grallery_page.dart';
import 'package:flutter_structure/modules/home/home_page.dart';
import 'package:flutter_structure/modules/plaza/plaza_page.dart';
import 'package:flutter_structure/modules/tabbar/tabbar_item.dart';
import 'package:flutter_structure/modules/user/user_page.dart';
import '../../common/config/config_path.dart';

class Tabbar extends StatefulWidget {
  const Tabbar({super.key});

  @override
  TabbarState createState() => TabbarState();
}

class TabbarState extends State<Tabbar> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  int currentIndex = 0;
  final List<Map<String, String>> tabItems = [
    {
      "defaultIcon": "${AppConfig.assetsMedia}home.png",
      "selectedIcon": "${AppConfig.assetsMedia}home-active.png",
      "label": "首页",
    },
    {
      "defaultIcon": "${AppConfig.assetsMedia}gallery.png",
      "selectedIcon": "${AppConfig.assetsMedia}gallery-active.png",
      "label": "作品",
    },
    {
      "defaultIcon": "${AppConfig.assetsMedia}plaza.png",
      "selectedIcon": "${AppConfig.assetsMedia}plaza-active.png",
      "label": "广场",
    },
     {
      "defaultIcon": "${AppConfig.assetsMedia}account.png",
      "selectedIcon": "${AppConfig.assetsMedia}account-active.png",
      "label": "账号",
    },
  ];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: tabItems.length, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  void onTabTapped(int index) {
    setState(() {
      currentIndex = index;
      if (_tabController.index != index) {
        _tabController.animateTo(index);
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: null,
      body: TabBarView(
        controller: _tabController,
        physics: const NeverScrollableScrollPhysics(),
        children: const [
          HomePage(),
          GralleryPage(),
          PlazaPage(),
          UserPage()
        ],
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed, // 设置类型 保证background 生效
        currentIndex: currentIndex,
        onTap: onTabTapped,
        items: tabItems.map((item) {
          final index = tabItems.indexOf(item);
          return BottomNavigationBarItem(
            icon: TabBarItem(
              defaultIconPath: item["defaultIcon"]!,
              selectedIconPath: item["selectedIcon"]!,
              isSelected: currentIndex == index,
            ),
            label: "",
          );
        }).toList(),
      ),
    );
  }
}
